/**
Copyright Christiaan Ottow 2009
chris@6core.net

See README for info
 
 This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package visim;

import java.io.*;
	
public class PostRequest extends HttpRequest
{
	private String host;
	private String path;
	private String filename;
	
	public PostRequest( String host, String path, String filename )
	{
		this.host = host;
		this.path = path;
		this.filename = filename;
	}
	
	public void send( DataOutputStream out ) throws IOException
	{
		File f = new File( filename );
		InputStream is = new FileInputStream( f );

		String mimehdr = "------IcebergFormBoundaryY059EJFGtzzIGQCs\n";
		mimehdr += "Content-Disposition: form-data; name=\"testfile\"; filename=\""+filename+"\"\n";
		mimehdr += "Content-Type: application/macbinary\n\n";

		String mimeend = "\n------IcebergFormBoundaryY059EJFGtzzIGQCs--\n";
		
		out.writeBytes( "POST "+path+" HTTP/1.1\n" );
		out.writeBytes( "Host: "+host+"\nConnection: close\n" );
		out.writeBytes( "User-Agent: Visim "+Visim.VERSION+"\n" );
		out.writeBytes( "Referer: http://" + host + "/" + path + "\n" );
		out.writeBytes( "Accept-Encoding: gzip, deflate\n" );
		out.writeBytes( "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\n" );
		out.writeBytes( "Content-Type: multipart/form-data; boundary=----IcebergFormBoundaryY059EJFGtzzIGQCs\n" );
		out.writeBytes( "Content-Length: "+(f.length()+mimehdr.length()+mimeend.length()) + "\n" );
		out.writeBytes( "\n" );
		
		// write mime boundary
		out.writeBytes( mimehdr );
		
		// begin data
		
		int numRead = 0;
		int bs = 256000;
		byte[] data = new byte[bs];
		while( is.available() > 0 )
		{
			numRead = is.read( data, 0, bs );
			out.write( data, 0, numRead );
			try {
				Thread.sleep( 500 );
			} catch( Exception e ) {
				System.err.println("Thread was unable to sleep");
			}
		}
		
		is.close();
		
		// end of file, print mime boundary
		out.writeBytes( mimeend );
		
		
	}

}
